#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>

#define BUFFER_SIZE 32

int main(int argc, char **argv) {
	if (argc < 4) {
		fprintf(stderr, "Not enough arguments: <server_ip> <message> <port> \n");
		return 1;
	}	
	
	int socket_handle;
	struct sockaddr_in echo_client;
	char buffer[BUFFER_SIZE];
	unsigned int echo_length;
	int received = 0;
	
	if ((socket_handle = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
		fprintf(stderr, "Socket couldn't be created.\n");
		return 1;
	}

	memset(&echo_client, 0, sizeof(echo_client));
	echo_client.sin_family = AF_INET;
	echo_client.sin_addr.s_addr = inet_addr(argv[1]);
	echo_client.sin_port = htons(atoi(argv[3]));

	if (connect(socket_handle, (struct sockaddr *) &echo_client, sizeof(echo_client)) < 0) {
		fprintf(stderr, "Couldn't connect to the server.\n");
		return 1;
	}

	echo_length = strlen(argv[2]);
	if (send(socket_handle, argv[2], echo_length, 0) != echo_length) {
		fprintf(stderr, "Wrong number of sent bytes.\n");
		return 1;
	}

	printf("Received: ");
	while (received < echo_length) {
		int bytes = 0;
		if ((bytes = recv(socket_handle, buffer, BUFFER_SIZE - 1, 0)) < 1) {
			fprintf(stderr, "Couldn't receive message response from server.\n");
			return 1;
		}
		received += bytes;
		buffer[bytes] = '\0';
		printf("%s", buffer);
	}

	printf("\n");
	close(socket_handle);
	
	return 0;
}
